package by.parfen.game.websocket.test;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

//@WebListener
@ServerEndpoint("/websocket-two/{ws-name}")
public class AnnotatedEndpointTwo {

	private static Set<Session> clients = Collections.synchronizedSet(new HashSet<Session>());

	@OnMessage
	public void onMessage(String message, Session session) throws IOException, InterruptedException {
		System.out.println("Message from " + session.getId() + ": " + message);

		synchronized (clients) {
			// Iterate over the connected sessions
			// and broadcast the received message
			for (Session client : clients) {
				System.out.println("Id: " + client.getId());
				if (!client.equals(session)) {
					try {
						client.getBasicRemote().sendText(message);
					} catch (IOException ex) {
						ex.printStackTrace();
					}
				}
			}
		}

		displayMap(session.getUserProperties());

	}

	private void displayMap(Map<String, Object> map) {
		Map<String, Object> hashMap = new HashMap<String, Object>();
		for (Map.Entry<String, Object> entry : hashMap.entrySet()) {
			System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
		}
	}

	@OnOpen
	public void onOpen(Session session, @PathParam("ws-name") String wsName) {
		clients.add(session);
		System.out.println(session.getId() + " has opened a connection with ws-name: " + wsName);
		try {
			session.getBasicRemote().sendText("Connection Established");
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	@OnClose
	public void onClose(Session session) {
		clients.remove(session);
		System.out.println("Session " + session.getId() + " has ended");
	}
}
